package lu.peersoft.timesheet
import groovy.swing.SwingBuilder;
import groovy.util.slurpersupport.NodeChild
import lu.peersoft.util.Mixins


/**
 * @author thor kummer
 *
 */
public class Timesheet{

    def configFileName = System.getProperty("configFile")
    def config = new XmlSlurper().parseText((configFileName as File).text)
    
    def MONTH = new Integer(config.timesheet.@month as String)
    def YEAR = new Integer(config.timesheet.@year as String)
    def HOME = config.timesheet.@home as String
    def TIMESHEET = new File("$HOME/${config.timesheet.@template}")
    def FILTER = config.timesheet.@filter as String
    def PROXY_PASSWORD = System.properties['http.proxy-password']
    def MS_PER_HOUR = 3600000
    
    def workDays = [:]
    def sum = 0
    def now = new Date()
        
    public static void main(String[] args) {
        Mixins.mixin()
        def timesheet = new Timesheet()
        timesheet.configure()
        timesheet.loadHours()
        timesheet.formatTemplate()
    }
    
    def configure() {
        Locale.setDefault(Locale.ENGLISH)
        if(config.proxySet == "true") {
            Authenticator.setDefault(new SimpleAuthenticator(config));
        }
    }
    
    def loadHours() {
        def googleCalendar = new GoogleCalendar(config)
        def startMin = new GregorianCalendar(YEAR, MONTH - 1, 1).time
        def startMax = new GregorianCalendar(YEAR, MONTH, 1).time
    
        googleCalendar.getFeed(startMin, startMax).each {
            if(it.description.toString() =~ FILTER) {
                def hours = (it.end.time-it.start.time) / MS_PER_HOUR
                println ">${it.start.date.format("00")} ${hours.format("00.00")} ${it.description}"
                addHours(workDays, it.start.date, hours)
                sum += hours
            }
        }
        println sum
    }
    
    def formatTemplate() {
        def hours
        def text = TIMESHEET.text
        (1..31).each {
            hours = workDays.containsKey(it) ? workDays[it] : 0
            text = text.replaceAll("<day$it>", hours.format("0.00"))
            // println "$it: $hours"
        }
        text = text.replaceAll("<month>", MONTH as String)
        text = text.replaceAll("<year>", YEAR as String)
        text = text.replaceAll("<totalhours>", sum.format("00.00"))
        text = text.replaceAll("<signdate>", now.format("MMM dd yyyy"))
        def out = new File("$HOME/timesheet-for-$YEAR-$MONTH-written-${now.format("yyyy-MM-dd")}.rtf")
        out.write(text)
        println "wrote $out"
    }

    def addHours(map, key, value) {
      if(map.containsKey(key))
        map[key] = map[key] + value
      else
        map[key] = value
    }
}


